//定义摇奖的人员 [名称，1亿次命中累加值，代表符号]
var orgAr=[["TOM",0,":看:"],["MOM",0,":吐舌:"],["LEE",0,":熊吉:"],["NEO",0,":呆无辜:"],["SHE",0,":白眼:"]];
var moneyTea="养生基金剩余: 36元 ";
var objCountTable = {};  //洗茶壶次数统计.

//保存数据
function saveCountTable(name) {
    objCountTable[name] ++;
    var jsonStr = JSON.stringify(objCountTable);
    pm.variables.set("countTable", jsonStr);

    var reg = new RegExp( '"' , "g" )
    jsonStr = jsonStr.replace(reg,"");
    console.log(jsonStr);
    return jsonStr;
}

//从服务端获取洗茶壶次数
function initCountTable(ar) {
    //统计当前命中人员次数

    //示例： {"TOM":2,"MOM":1,"LEE":1,"NEO":2,"SHE":5}

    var oldCountTableStr = pm.variables.get("countTable");
    console.log("countTable:"+oldCountTableStr);
    if(oldCountTableStr != null && oldCountTableStr.length>5){
        objCountTable = JSON.parse(oldCountTableStr);
    }

    //初使化数据
    for(var i=0; i<ar.length; i++){
        var coutVal = objCountTable[ar[i][0]];
        if(coutVal==null) {
            objCountTable[ar[i][0]] = 0;
        }
    }
    console.log(objCountTable);
}

/**
 * 主程序
 */
function main(){

    //获取已洗茶壶次数. 数据将保存在 objCountTable 对象中. 不对orgAr产生影响.
    initCountTable(orgAr);

    //随机排列人员位置.
    for (var i=0;i<orgAr.length;i++){
        var index = Math.floor(Math.random() * orgAr.length);
        var temp = orgAr[i];
        orgAr[i] = orgAr[index];
        orgAr[index] = temp;
    }

    var ar = orgAr;
    var randNum = 100000000;

    //随机命中率统计
    for (var i=0;i<randNum;i++)
    {
        var index = Math.floor(Math.random() * ar.length); 
        ar[index][1] = ar[index][1]+1
    }

    ///信息输出
    var boyListInfo = ""
    for(var i=0;i<ar.length; i++) {
        boyListInfo = boyListInfo + ar[i][0]+",";
    }

    var outStr=":撒花::撒花::撒花::撒花::撒花::撒花::撒花:\\n"+"排位:["+boyListInfo+"]\\n一亿"+"次随机命中统计(最高者得):\\n"

    //命中率高低排序
    var sortList=ar.sort(function(a,b){
                return b[1] - a[1];
            });

    //保存结果到服务器上
    saveCountTable(sortList[0][0])

    for (var i=0;i<sortList.length;i++)
    {
        var curinfoStr = ">>>["+ objCountTable[sortList[i][0]] +"次]"+", "+sortList[i][0] +sortList[i][2]+": " + sortList[i][1] + "\\n";
        outStr = outStr + curinfoStr;
    }

    //将数据输出到飞书群中.
    outStr = outStr + ":完成::完成::完成::完成::完成::完成::完成:\\n";
    outStr = outStr + moneyTea + "\\n";

    //设置相关变量
    pm.variables.set("teaName",sortList[0][0]);
    pm.variables.set("infoStr",outStr);

    //算法完成.

}

//执行main.

main();